package com.example.malllocationserver.utils;

import com.example.malllocationserver.entity.data.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ParticleFilter {
    public List<Integer> weight = new ArrayList<>();
    public Split sp = new Split();
    public List<Map<String , Integer>> WifiList = new ArrayList<>();
    public List<String> name = new ArrayList<>();
    private List<String> Wifi = null;
    public List<Data> dataList = new ArrayList<>();
    public Map<String,Integer>target;
    public List<Integer> distanceList = new ArrayList<>();
    public operation op = new operation();
    private  double threshold = 0.7;
    public ParticleFilter(List<Data> data,Map<String,Integer>target){
        this.dataList = data;
        this.target = target;
        setName();
        setWifi();
        setDistance();
        setWeight();
    }

    public void setWifi(){
        for(Data _data:dataList){
            WifiList.add(sp.WifiSplit(_data.getWifi()));
        }
    }
    public void setName(){
        for(Data _data:dataList)
            name.add(_data.getSerial());
    }
    public void setDistance(){
        for(Map<String,Integer> map:WifiList)
            distanceList.add(op.distance_wifi(target,map)[0]);
    }
    public void setWeight(){
        int sum = 0;
        for(int distance : distanceList)
            sum += distance;
        for(int distance : distanceList)
            weight.add(distance/sum);
    }
    public double[] getLocation(){
        List<Data> newData = new ArrayList<>();
        List<Integer> newWeight = new ArrayList<>();
        for(int i=0;i<dataList.size();i++)
            if(weight.get(i)>=threshold){
                newData.add(dataList.get(i));
                newWeight.add(weight.get(i));
            }
        double xLoad = 0,yLoad = 0;
        for(int i=0;i<newData.size();i++){
            double x = newData.get(i).getX();
            double y = newData.get(i).getY();
            xLoad += x*newWeight.get(i);
            yLoad += y*newWeight.get(i);
        }
        resample(newData);
        return new double[]{xLoad,yLoad};
    }
    public void resample(List<Data> newData){
        dataList = newData;
        setWifi();
        setName();
        setDistance();
        setWeight();
    }
}
